package com.lushuan.ch10_springboot_security.service;

import com.lushuan.ch10_springboot_security.dao.ProjectRepository;
import com.lushuan.ch10_springboot_security.dao.UserRepository;
import com.lushuan.ch10_springboot_security.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ProjectRepository projectRepository;

    // 要求用户具有ADMIN角色才能访问
    @PreAuthorize("hasRole('ADMIN')")
    public List<UserDTO> getAllUsers() {
        return userRepository.findAll();
    }

    // 要求用户具有USER角色，并且只能访问自己的数据
    @PreAuthorize("hasRole('USER') and #userId == authentication.principal.id")
    public UserDetails getUserDetails(Long userId) {
        return userRepository.findById(userId);
    }

    // 组合多个条件
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER') and hasPermission(#project, 'READ')")
    public ProjectDetails getProjectDetails(Project project) {
        return projectRepository.findByProject(project);
    }

    // 方法执行后的权限检查
    @PostAuthorize("returnObject.userId == authentication.principal.id")
    public UserDetails loadUserById(Long id) {
        return userRepository.findById(id);
    }

    public UserDTO getUserInfo(String username) {
        return new UserDTO();
    }
}